package com.echartsdata.demos.web;

import com.alibaba.fastjson2.JSONObject;
import com.echartsdata.Entity.User;
import com.echartsdata.Entityimp.Userimp;
import com.echartsdata.security.JwtResponse;
import com.echartsdata.security.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class JwtAuthenticationController {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationController.class);

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService jwtUserDetailsService;
    //登录
    @PostMapping("/authenticate")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody User authenticationRequest) {
        try {
            logger.info("尝试认证用户: {}", authenticationRequest.getUsername());

            // 执行认证
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            authenticationRequest.getUsername(),
                            authenticationRequest.getPassword())
            );

            logger.info("用户认证成功: {}", authenticationRequest.getUsername());

            // 生成令牌
            final UserDetails userDetails = jwtUserDetailsService
                    .loadUserByUsername(authenticationRequest.getUsername());

            final String token = jwtTokenUtil.generateToken(userDetails);

            logger.info("为用户生成令牌: {}", authenticationRequest.getUsername());

            return ResponseEntity.ok(new JwtResponse(token));

        } catch (BadCredentialsException e) {
            logger.error("认证失败: 用户名或密码不正确", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("认证失败: 用户名或密码不正确");
        } catch (Exception e) {
            logger.error("认证过程中发生错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("认证过程中发生错误");
        }
    }
    @Resource
    private Userimp userimp;
    @Autowired
    private PasswordEncoder passwordEncoder; // 注入密码编码器
    // 注册接口
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        //json数据处理
        JSONObject jsonObject = new JSONObject();
        if (user != null && user.getUsername()!=null &&  user.getPassword()!=null ) {
            if (userimp.get_user(user.getUsername()) != null) {
                jsonObject.put("code", 403);
                jsonObject.put("info", "已经存在用户名为:"+user.getUsername());
                logger.info("已经存在用户名为:{}", user.getUsername());
            }
            else {
                // 1. 加密密码
                String encodedPassword = passwordEncoder.encode(user.getPassword());
                //加入实体类
                user.setPassword(encodedPassword);
                userimp.registerUser(user.getUsername(), user.getPassword());
                jsonObject.put("code", 200);
                jsonObject.put("info", "用户注册成功！");
                logger.info("用户注册成功");

            }

        }
        else {
            jsonObject.put("code", 403);
            jsonObject.put("info", "用户名或密码不能为空");
        }
        return jsonObject.toJSONString();
    }
}